package handlers

import (
	"encoding/json"
	"net/http"
	"strings"

	"homepage-backend/internal/config"
	"homepage-backend/internal/models"
	"homepage-backend/internal/services"
)

// SitesHandler 处理站点列表请求和管理
func SitesHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		sites, err := services.LoadSites(config.GlobalConfig.SitesFilePath)
		if err != nil {
			services.LogError("加载站点数据失败: %v", err)
			http.Error(w, "加载站点数据失败", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(sites)
		return
	}
	// 仅签权接口允许增删改
	if r.Method == "POST" || r.Method == "PUT" || r.Method == "DELETE" {
		// 统一JWT签权
		AdminAuthMiddleware(sitesHandlerWrite)(w, r)
		return
	}
}

// sitesHandlerWrite 仅用于POST/PUT/DELETE，已通过JWT校验
func sitesHandlerWrite(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		var site models.Site
		if err := json.NewDecoder(r.Body).Decode(&site); err != nil {
			http.Error(w, "请求数据无效", http.StatusBadRequest)
			return
		}
		err := services.AddSite(config.GlobalConfig.SitesFilePath, site)
		if err != nil {
			http.Error(w, "添加失败", http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusCreated)
		w.Write([]byte("ok"))
	case "PUT":
		var site models.Site
		if err := json.NewDecoder(r.Body).Decode(&site); err != nil {
			http.Error(w, "请求数据无效", http.StatusBadRequest)
			return
		}
		err := services.UpdateSite(config.GlobalConfig.SitesFilePath, site)
		if err != nil {
			http.Error(w, "修改失败", http.StatusInternalServerError)
			return
		}
		w.Write([]byte("ok"))
	case "DELETE":
		id := r.URL.Query().Get("id")
		if id == "" {
			http.Error(w, "缺少id参数", http.StatusBadRequest)
			return
		}
		err := services.DeleteSite(config.GlobalConfig.SitesFilePath, id)
		if err != nil {
			http.Error(w, "删除失败", http.StatusInternalServerError)
			return
		}
		w.Write([]byte("ok"))
	default:
		http.Error(w, "方法不允许", http.StatusMethodNotAllowed)
	}
}

// HomeHandler 处理首页请求
func HomeHandler(w http.ResponseWriter, r *http.Request) {
	// 获取客户端IP
	clientIP := r.Header.Get("X-Real-IP")
	if clientIP == "" {
		clientIP = r.RemoteAddr
		if i := strings.LastIndex(clientIP, ":"); i != -1 {
			clientIP = clientIP[:i]
		}
	}

	// 查询IP地理位置
	location, err := services.SearchIP(clientIP)
	if err != nil {
		location = "未知位置"
	}

	// 加载站点数据
	sites, err := services.LoadSites(config.GlobalConfig.SitesFilePath)
	if err != nil {
		http.Error(w, "Failed to load sites", http.StatusInternalServerError)
		return
	}

	// 构造响应数据
	response := struct {
		Location string        `json:"location"`
		PageData interface{}   `json:"pagedata"`
		Sites    []models.Site `json:"sites"`
	}{
		Location: location,
		PageData: config.GlobalConfig.PageData,
		Sites:    sites,
	}

	// 返回JSON响应
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}
